﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using Kaskelot.SP.Core;
using Kaskelot.SP.Model.Client.Forms;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientMaterielTypExtensions
	{
		public static ClientMaterielTyp ToClientContract(this MaterielTyp entity)
		{
			ClientMaterielTyp b = new ClientMaterielTyp();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientMaterielTyp ToMinimalClientContract(this MaterielTyp entity)
		{
			ClientMaterielTyp b = new ClientMaterielTyp();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static MaterielTyp ToContract(this ClientMaterielTyp b)
		{
			MaterielTyp entity = new MaterielTyp();

			CopyToEntity(b, entity);

			return entity;
		}

		public static MaterielTyp UpdateContract(this MaterielTyp mt, MaterielTypForm form)
		{
			if (mt.Id == Guid.Empty)
			{
				mt.Id = Guid.NewGuid();
			}

			mt.Beskrivning = form.Beskrivning;
			mt.VisaILista = form.VisaILista;

			return mt;
		}

		private static void CopyFromEntity(MaterielTyp from, ClientMaterielTyp to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Beskrivning = from.Beskrivning;
			to.VisaILista = from.VisaILista.ToJaNej();

			to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
			to.SkapadAv = from.SkapadAv;
		}

		private static void CopyToEntity(ClientMaterielTyp from, MaterielTyp to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Beskrivning = from.Beskrivning;
			to.VisaILista = from.VisaILista.FromJaNej();

			if (!String.IsNullOrEmpty(from.Andrad))
				to.Andrad = DateTime.Parse(from.Andrad);
			else
				to.Andrad = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = DateTime.Parse(from.Skapad);

			to.SkapadAv = from.SkapadAv;
		}
	}
}
